package com.auto.qinglong.ui.viewmodel

import android.util.Log
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import com.auto.base.net.ResultWrapper
import com.auto.base.ui.BaseViewModel
import com.auto.qinglong.net.client.QlRepository
import com.auto.qinglong.net.client.beans.Task
import com.auto.qinglong.net.client.beans.TaskGroupTagBean
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class HomeUiState(
    val groupTags: List<TaskGroupTagBean> = listOf(),
    val expandedTaskId: String = "",
    val selectTags: TaskGroupTagBean? = null, val refreshList: Boolean = false
)

data class HomeViewModelState(
    val groupTags: List<TaskGroupTagBean> = listOf(),
    val expandedTaskId: String = "",
    val selectTags: TaskGroupTagBean? = null, val refreshList: Boolean = false
) {
    fun toUiState(): HomeUiState = HomeUiState(groupTags, expandedTaskId, selectTags, refreshList)
}

/**
 * Created by YuanWei1 on 2025/6/12.
 *
 * Description:
 */
@HiltViewModel
class HomeViewModel @Inject constructor(val qlRepository: QlRepository) : BaseViewModel() {
    private val viewModelState = MutableStateFlow(
        HomeViewModelState()
    )

    // UI state exposed to the UI
    val uiState = viewModelState.map(HomeViewModelState::toUiState)
        .stateIn(
            viewModelScope, SharingStarted.Eagerly, viewModelState.value.toUiState()
        )

    val pageFlow = viewModelState.map { it.selectTags }
        .distinctUntilChanged()
        .flatMapLatest {
            qlRepository.getTaskPager("", bean = it).flow
        }
        .cachedIn(viewModelScope)

    private val _refreshListEvent = MutableSharedFlow<Unit>()
    val refreshListEvent = _refreshListEvent.asSharedFlow()

    init {
        getTags()
    }

    private fun getTags() {
        viewModelScope.launch {
            when (val result = qlRepository.getViews()) {
                is ResultWrapper.Success<List<TaskGroupTagBean>> -> {
                    val tags = result.data
                    if (!tags.isNullOrEmpty()) {
                        viewModelState.update {
                            it.copy(groupTags = tags)
                        }
                    }
                }

                is ResultWrapper.Error -> {
                    Log.d("====", result.exception.message.toString())
                    result.exception.message?.let { showToast(it) }
                }
            }
        }
    }

    fun saveSelectTaskGroupTagBean(bean: TaskGroupTagBean) {
        viewModelState.update {
            it.copy(selectTags = bean)
        }
    }
//
//    fun getTask(search: String = "", pager: Int = 1) {
////        viewModelState.update {
////            it.copy(isRefreshing = true)
////        }
//        viewModelScope.launch {
//            val result = qlRepository.getTask(
//                search, pager, 30, viewModelState.value.selectTags
//            )
//            if (result is ResultWrapper.Success) {
//                result.data?.let { data ->
//                    val tasks = data.data?.map { it.toTask() }
//                    if (tasks != null) {
////                        viewModelState.update { state ->
////                            state.copy(dataList = tasks, isRefreshing = false)
////                        }
//                    }
//                }
//            } else if (result is ResultWrapper.Error) {
//                result.exception.message?.let { showToast(it) }
////                viewModelState.update { state ->
////                    state.copy(isRefreshing = false)
////                }
//            }
//        }
//    }

    fun runTask(task: Task) {
        setLoading(true)
        viewModelScope.launch {
            val result = qlRepository.runTask(listOf(task.key))
            setLoading(false)
            if (result is ResultWrapper.Success) {
                showToast("运行成功")
                _refreshListEvent.emit(Unit)
            } else if (result is ResultWrapper.Error) {
                result.exception.message?.let { showToast(it) }
            }
        }
    }

    fun updateExpandedTaskId(key: String) {
        viewModelState.update {
            it.copy(expandedTaskId = key)
        }
    }


    fun deleteTask(item: Task) {
        viewModelScope.launch {
            val result = qlRepository.deleteTask(item)
            when (result) {
                is ResultWrapper.Success -> {
                    showToast("删除成功！")
                    _refreshListEvent.emit(Unit)
                    viewModelState.update {
                        it.copy(expandedTaskId = "")
                    }
                }

                is ResultWrapper.Error -> {
                    showToast("删除失败！")
                }
            }
        }
    }
}